package com.mcxx.common.interceptor;

import com.mcxx.common.exception.BizException;
import com.yinhai.ta404.core.autoconfigure.TaSystemProperties;
import com.yinhai.ta404.core.restservice.BaseRestService;
import com.yinhai.ta404.core.restservice.resultbean.ResultBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
@Order(100)
public class DefaultRestServiceExceptionInterceptor extends BaseRestService{
    private static final Logger logger = LoggerFactory.getLogger(DefaultRestServiceExceptionInterceptor.class);
    @Autowired
    private TaSystemProperties taSystemProperties;

    @ExceptionHandler({BizException.class})
    @ResponseBody
    public ResultBean appExceptionHandler(BizException exception) {
        String errorMsgs = exception.getMessage();
        if (null == errorMsgs) {
            if (logger.isErrorEnabled()) {
                logger.error("MCException msg = {},return default message", errorMsgs);
            }

            return this.interServerError();
        } else {
            this.setErrors(exception.getErrCode(), new String[]{errorMsgs});
            this.setSuccess(false);
            if (logger.isErrorEnabled()) {
                logger.error("MCException msg = {},exception = {}", exception.getMessage(), exception);
            }

            return this.result();
        }
    }
    private ResultBean interServerError() {
        this.setError("500", this.taSystemProperties.getInterErrorMsg());
        this.setSuccess(false);
        return this.result();
    }
}
